﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dao;
using Model;

namespace Service.Impl
{
    public class BaseServiceImpl<M, T> : BaseService<M, T>
    {
        private BaseDao<M, T> dao = null;
        public CommandContext CommandContext { get; set; }
        public BaseServiceImpl()
        {

        }        
        public BaseServiceImpl(BaseDao<M, T> baseDao)
        {
            this.dao = baseDao;
        }

        protected void SetDao(BaseDao<M, T> baseDao)
        {
            this.dao = baseDao;
        }

        public BaseResult<int> Delete(M m)
        {
            int res = dao.Delete(m);
            if(res > 0)
            {
                return BaseResultFactory.CreateSuccess<int>(res);
            }
            else
            {
                return BaseResultFactory.CreateFail<int>(BaseResultCode.CODE_DELETE_FAILURE, "删除数据失败!");
            }
        }

        public BaseResult<int> Save(T t)
        {
            int res = dao.Save(t);
            if (res > 0)
            {
                return BaseResultFactory.CreateSuccess<int>(res);
            }
            else
            {
                return BaseResultFactory.CreateFail<int>(BaseResultCode.CODE_ADD_FAILURE, "新增数据失败!");
            }
        }

        public BaseResult<List<T>> Search(T t)
        {
            List<T> list = dao.Search(t);
            return BaseResultFactory.CreateSuccess<List<T>>(list);
        }

        public BaseResult<T> SearchByPrimaryKey(M m)
        {
            T t = dao.SearchByPrimaryKey(m);
            return BaseResultFactory.CreateSuccess<T>(t);
        }

        public BaseResult<T> SearchOne(T t)
        {
            T res = dao.SearchOne(t);
            return BaseResultFactory.CreateSuccess<T>(res);
        }

        public BaseResult<int> Update(T t)
        {
            int res = dao.Save(t);
            if (res > 0)
            {
                return BaseResultFactory.CreateSuccess<int>(res);
            }
            else
            {
                return BaseResultFactory.CreateFail<int>(BaseResultCode.CODE_UPDATE_FAILURE, "修改数据失败!");
            }
        }
    }
}
